<?php
/**
 * Created by PhpStorm.
 * User: wufeng
 * Date: 2021/8/22
 * Time: 23:25
 */

namespace Wufeng\Healthkit\Data;


class Healthkit
{

    /**
     * PHP操作dataCollector数据
     *
     * @param $accessToken     请求需要的token
     * @param $url             请求url
     * @param $type            操作类型
     * @param $dataCollectorId 请求的dataCollectorId
     * @param $dataPath        dataCollector存储路径
     *
     * @return response
     */
    private function http_request($accessToken, $url, $type, $dataCollectorId, $dataPath)
    {
        //入参判空
        if (empty($url) || empty($type) || empty($accessToken)) {
            echo "One of essential data is empty.";
            return false;
        }

        $ch = curl_init();//初始化curl
        $timeout = 10;// 超时时间（单位:s）
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//将结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//设置超时时间
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);//请求提交方式
        if (!empty($dataCollectorId)) {
            $url = $url . "/" . $dataCollectorId;//将dataCollectorId拼接到url后面
            curl_setopt($ch, CURLOPT_URL, $url);//请求url地址
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);//请求url地址
        }
        //根据对应的请求类型组装对应的请求参数
        switch ($type) {
            case "GET" :
            case "DELETE":
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: Bearer ' . $accessToken
                    )
                );
                break;
            case "POST":
            case "PUT" :
                if (empty($dataPath)) {
                    return false;
                }
                $postdata = file_get_contents($dataPath);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: Bearer ' . $accessToken,
                        'Content-Length: ' . strlen($postdata)
                    )
                );
                break;
        }
        $file_contents = curl_exec($ch);//运行curl，并获得返回值
        curl_close($ch);
        return $file_contents;
    }
}
